
import store from "@/store";
import { apiGet, apiPost, apiPut, apiDelete, apiDs, apiExport, apiDownload } from "@/api/openapi";

export default {
    data() {
        return {
            moduleCode: null,
            moduleInfo: {},
            userId: null,
            fieldList: null,
            // 遮罩层
            loading: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表格数据
            dataList: [],
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 弹出层标题
            formTitle: "",
            // 是否显示弹出层
            formAction: null,
            formData: null,
            dataOptions: [],
            queryExp:{},
            pager: {
                page: 1,
                limit: 10,
                order: "id desc",
            },
            upload: false,
            apply: null
        };
    },
    created() {
        const moduleCode = this.$route.query && this.$route.query.code;
        if (!moduleCode) {
            this.$modal.msgError("参数错误");
            return;
        }
        this.moduleCode = moduleCode;
        let params = {
            "dev_module": {
                code: moduleCode
            },
            "dev_module_field": {
                module_id: "@dev_module.id",
                "@pager": { limit: 100, order: "sorts ASC" }
            }
        }
        apiGet(params).then(response => {
            this.moduleInfo = response.data['dev_module'];
            this.fieldList = response.data['dev_module_field'];
            this.initField();      
        });
        this.userId = store.getters.userId;
    },
    methods: {
        /** 查询列表 */
        getList() {
            this.loading = true;
            
            let modelCode = this.moduleInfo['api_model'];
            let params = {"@pager":this.pager};
            let p =  { ...this.queryParams, '@alias':"t", "@exp": this.queryExp };
            if (this.moduleInfo['api_ds'] && this.moduleInfo['api_ds'].trim()) {
                let ds = JSON.parse(this.moduleInfo['api_ds']);
                if(ds[modelCode]){
                    //一般是默认查询条件
                    for(var k in ds[modelCode]){
                        p[k] = ds[modelCode][k];
                    }
                    delete ds[modelCode];
                }
                params = Object.assign(params, ds);
            }
            params[modelCode] = p;
            apiGet(params).then(response => {
                this.dataList = response.data.rows;
                this.total = response.data.total;
                this.loading = false;
            });
        },
        dictLabel(field, dataVal) {
            if(dataVal == null || dataVal == ''){
                return '';
            }

            let vs = dataVal.split(',');
            let dataStr = '';
            vs.forEach(v=>{
                for(var i=0;i<this.dataOptions[field].length;i++){
                    if(this.dataOptions[field][i]['value'] == v){
                        dataStr += ',' + this.dataOptions[field][i]['label'];
                    }
                }
            });
            return dataStr.length > 0 ? dataStr.substring(1) : dataStr;
        },
        initField() {
            let ps = [];
            let exp = {};
            let that = this;
            for (var i = 0; i < this.fieldList.length; i++) {
                if (this.fieldList[i].list == 'N') {
                    continue;
                }
                let field = this.fieldList[i];
                if (field.type == "radio" || field.type == "checkbox") {
                    ps.push(new Promise((resolve, reject) =>{
                        apiDs('sys_dict_select',{dict:field.ds}).then((res) => {
                            that.dataOptions[field.code] = res.data;
                            resolve();
                        });
                    }));
                }
                if(field.search != '0'){
                    exp[field.code] = field.search;
                }
            }
            this.queryExp = exp;
            if(ps.length > 0){
              Promise.all(ps).then(res=>{
                this.getList();    
              })
            }else{
                this.getList();
            }
        },
        // 取消按钮
        cancel() {
            this.formAction = null;
            this.formData = null;
        },
        /** 搜索按钮操作 */
        handleQuery(params) {
            this.pager.page = 1;
            this.queryParams = params;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery({});
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.formData = {};
            this.formAction = 'add';
            this.formTitle = "添加" + this.moduleInfo['name'];
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.formData = row;
            this.formAction = 'edit';
            this.formTitle = "修改" + this.moduleInfo['name'];
        },
        /** 查看按钮操作 */
        handleView(row) {
            this.formData = row;
            this.formAction = 'view';
            this.formTitle = "查看" + this.moduleInfo['name'];
        },
        /** 提交审批按钮操作 */
        handleApply(row) {
          this.apply = {
            "data_id":row.id,
            "flow_model": this.moduleInfo['api_model'],
            "title": "提交 " + this.moduleInfo['name'],
            "reason": row.reason
          }
        },
        /** 提交按钮 */
        submitForm(form) {
            let data = {};
            data[this.moduleInfo['api_model']] = form;
            data['@tags'] = [this.moduleInfo['api_model']];
            if (form.id != null) {
                apiPut(data).then(response => {
                    this.$modal.msgSuccess("修改成功");
                    this.cancel();
                    this.getList();
                });
            } else {
                apiPost(data).then(response => {
                    this.$modal.msgSuccess("新增成功");
                    this.cancel();
                    this.getList();
                });
            }
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            let that = this;
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除选中的' + that.moduleInfo['name'] + '数据？').then(function () {
                let data = {};
                data[that.moduleInfo['api_model']] = { id: ids, "@exp": { id: "in" } };
                data['@tags'] = [that.moduleInfo['api_model']];
                return apiDelete(data);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch((e) => {
                console.log(e);
             });
        },
        /** 导入按钮操作 */
        handleImport() {
            this.upload = true;
        },
        importSuccess(msg) {
            this.upload = false;
            this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
            this.getList();
        },
        importCancel() {
            this.upload = false;
        },
        /** 导出按钮操作 */
        handleExport() {
            let params = {...this.queryParams};
            params["@table"] = this.moduleInfo['api_model']; 
            params['@pager'] = { page: 1, limit: 10000 };
            apiExport(params).then(response => {
                apiDownload(response.msg);
            });
        },
        /** 申请审批成功 */
        applySuccess(msg) {
            this.getList();
            this.apply = null;
        },
        applyCancel() {
            this.apply = null;
        }
    }
}